import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/constants'
import { apiLogin } from '@/api/user'

const state = {
  token: '', // token
  name: '', // 名称
  avatar: '', // 头像
  info: {}, // 用户信息
  menus: [] // 用户菜单
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_INFO: (state, info) => {
    state.info = info
  },
  SET_MENUS: (state, menus) => {
    state.menus = menus
  }
}

const actions = {
  /**
   * 用户登录
   */
  login ({ commit }, params) {
    return new Promise((resolve, reject) => {
      apiLogin(params).then(response => {
        var token = response.result['Access-Token']
        Vue.ls.set(ACCESS_TOKEN, token, 7 * 24 * 60 * 60 * 1000)
        commit('SET_TOKEN', token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  /**
   * 获取用户信息
   */
  getUserInfo ({ commit }) {
    return new Promise((resolve, reject) => {
      commit('SET_NAME', '椎疯少年')
      commit('SET_INFO', {
        phone: '13568875217',
        address: '四川省成都市'
      })
      resolve()
    })
  },

  /**
   * 获取用户菜单
   */
  setUserMenus ({ commit }, userMenus) {
    return new Promise((resolve, reject) => {
      commit('SET_MENUS', userMenus)
      resolve()
    })
  },

  /**
   * 退出登录
   */
  logout ({ commit }) {
    return new Promise((resolve, reject) => {
      commit('SET_TOKEN', '')
      commit('SET_NAME', '')
      commit('SET_MENUS', [])
      Vue.ls.remove(ACCESS_TOKEN)
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
